package com.prim.threadcoreknowledge.sixstater;

/**
 * 展示 Blocked Waiting TimedWaiting 三种状态
 *
 * @author prim
 */
public class BlockedWaitingTimedWaiting implements Runnable {

    public static void main(String[] args) {
        BlockedWaitingTimedWaiting runnable = new BlockedWaitingTimedWaiting();
        Thread thread1 = new Thread(runnable);
        thread1.start();
        Thread thread2 = new Thread(runnable);
        thread2.start();
        //打印出 TimedWaiting状态 因为正在执行Thread.sleep(1000)
        System.out.println(thread1.getState());
        //打印出 Blocked状态，因为thread2想要拿到synchronized锁却拿不到。
        System.out.println(thread2.getState());
        try {
            Thread.sleep(1300);
        } catch (InterruptedException e) {
            e.printStackTrace();
        }
        //打印出Waiting状态 因为thread1 休眠1后 又执行了wait()方法 thread1处于waiting状态
        System.out.println(thread1.getState());
    }

    @Override
    public void run() {
        //线程1 拿到锁 休眠
        //线程2 没有拿到锁 blocked 状态
       syn();
    }

    private synchronized void syn(){
        try {
            Thread.sleep(1000);
            wait();
        } catch (InterruptedException e) {
            e.printStackTrace();
        }
    }
}
